package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleConfigService;
import com.heima.article.service.ApArticleContentService;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ApUserFollowConstans;
import com.heima.common.constants.ArticleConstants;
import com.heima.feign.apUser.ApUserFollowClient;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVo;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.utils.thread.ApUserThreadUtil;
import org.apache.kafka.clients.KafkaClient;
import org.checkerframework.checker.units.qual.K;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: JW
 * @Description: TODO
 * @DateTime: 2022/1/22 19:20
 **/
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper,ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleConfigService apArticleConfigService;

    @Autowired
    private ApArticleContentService apArticleContentService;

    @Autowired
    private ArticleFreemarkerService articleFreemarkerService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ApUserFollowClient apUserFollowClient;


    @Override
    public ResponseResult getApArticle(Integer type, ArticleHomeDto dto) {


        List<ApArticle> apArticles = apArticleMapper.loadArticleList(type, dto);

        return ResponseResult.okResult(apArticles);
    }

    /**
     * @param articleDto
     * @Author: JW
     * @Description: TODO 保存文章 &&修改
     * @Date: 19:08 2022-02-14
     * @Param: [articleDto]
     * @return: com.heima.model.common.dtos.ResponseResult
     */
    @Override
    @Transactional
    public ResponseResult saveArticle(ArticleDto articleDto) {

        //参数校验
        if (articleDto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApArticle apArticle = null;

        Long articleId = null;

        if (articleDto.getId() == null){
            //保存文章
            apArticle = new ApArticle();

            BeanUtils.copyProperties(articleDto,apArticle);

            save(apArticle);

            //保存文章配置
            ApArticleConfig apArticleConfig = new ApArticleConfig();
            apArticleConfig.setArticleId(apArticle.getId());
            apArticleConfig.setIsComment(true);
            apArticleConfig.setIsForward(true);
            apArticleConfig.setIsDown(false);
            apArticleConfig.setIsDelete(false);

            apArticleConfigService.save(apArticleConfig);

            //保存文章内容
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(articleDto.getContent());

            apArticleContentService.save(apArticleContent);

            articleId = apArticle.getId();

            //异步调用 生成静态页
            articleFreemarkerService.buildArticleToMinIO(apArticle,articleDto.getContent());

        }else {
            //修改文章
            apArticle = getById(articleDto.getId());
            if (apArticle != null){
                //修改文章
                BeanUtils.copyProperties(articleDto,apArticle);
                updateById(apArticle);

                articleId = apArticle.getId();

                //修改文章内容
                apArticleContentService.update(Wrappers.lambdaUpdate(ApArticleContent.class)
                        .eq(ApArticleContent::getArticleId,apArticle.getId()));

                //异步调用 生成静态页
                articleFreemarkerService.buildArticleToMinIO(apArticle,articleDto.getContent());
            }

        }

        //返回文章id给
        return ResponseResult.okResult(articleId);
    }

    @Override
    public ResponseResult collect(CollectionBehaviorDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //hash大key,区分哪篇文章
        String key = ApUserFollowConstans.Article_Collection_key + dto.getEntryId();
        //hash小key,区分谁收藏了文章
        String hashKey = ApUserFollowConstans.Article_Fowllow_key
                + ApUserThreadUtil.getUser().getId();

        //判断是收藏还是取消收藏
        if (dto.getOperation() == 0) {
            redisTemplate.opsForHash().put(key, hashKey, "1");
        } else if (dto.getOperation() == 1) {
            redisTemplate.opsForHash().delete(key, hashKey);
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    /**
     * 加载用户行为数据
     */
    public ResponseResult loadBehavior(ArticleInfoDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
                 /*"islike":false,
                "isunlike":false,
                "iscollection":false,
                "isfollow":false*/
        Map<String, Boolean> map = new HashMap<>();
        //查找是否点赞
        String likeKey = ApUserFollowConstans.Article_Like_key + dto.getArticleId();
        String likeHashKey = ApUserFollowConstans.Like_Fowllow_key
                + ApUserThreadUtil.getUser().getId();
        Boolean aLikeKey = redisTemplate.opsForHash().hasKey(likeKey, likeHashKey);
        map.put("islike", aLikeKey ? true : false);

        String unLikeKey = ApUserFollowConstans.Article_Dislike_key + dto.getArticleId();
        String unLikeHashKey = ApUserFollowConstans.Dislike_Fowllow_key
                + ApUserThreadUtil.getUser().getId();
        Boolean aUnlikeKey = redisTemplate.opsForHash().hasKey(unLikeKey, unLikeHashKey);
        map.put("isunlike", aUnlikeKey ? true : false);

        String collectionKey = ApUserFollowConstans.Article_Collection_key + dto.getArticleId();
        String collectionHashKey = ApUserFollowConstans.Article_Fowllow_key
                + ApUserThreadUtil.getUser().getId();
        Boolean aCollectionKey = redisTemplate.opsForHash().hasKey(collectionKey, collectionHashKey);
        map.put("iscollection", aCollectionKey ? true : false);

        /*String fowllowKey = ApUserFollowConstans.App_User__INTERACT_KEY + dto.getAuthorId();
        String fowllowHashKey = ApUserFollowConstans.App_User_Fowllow_key
                + ApUserThreadUtil.getUser().getId();
        Boolean aFowllowKey = redisTemplate.opsForHash().hasKey(fowllowKey, fowllowHashKey);
        map.put("isfollow", aCollectionKey ? true : false);*/

        ApUserFollow apFollow = apUserFollowClient.getFollowInfo(ApUserThreadUtil.getUser().getId(), dto.getAuthorId());

        map.put("isfollow", apFollow!=null ? true : false);

        return ResponseResult.okResult(map);


    }
}
